package org.wattdepot.cli;

import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.resource.source.jaxb.Source;
import java.util.List;
import java.util.ArrayList;

/**
 * A class that prints out all the sources of wattdepot project.
 * @author Wing Cheung Ma, Edwin Lim
 *
 */
public class ListSources extends CommandLineInterface implements WattDepotCliCommand {
  /**
   * Lists information about all of the public power sources that are available on this server.
   * @param args list of strings input
   * @throws BadXmlException 
   * @throws NotAuthorizedException 
   * @return a string with all the sources in the grid
   */
  @Override
  public String doCommand(List<String> args) {
    
    List<Source> sources;
      
    try {
    sources = client.getSources();
    List<Source> parentList = new ArrayList<Source>();

    String parent = "";
    // sets the print format
    String format = "%1$-20s" + "%2$-20s" + "%3$-20s" + "\n";
    System.out.format(format, "Name", "Parent", "Description");
    // Gets the power plants that are parents
    for (Source source : sources) {
      if (source.getSubSources() == null) {
        parent = "";
      } 
      else {
        // add the parent power plants to the parent array list
        parentList.add(source);
      }
    }
    // go thru each source available.
    for (Source source : sources) {
      // sets the parent power to have no parents themselves
      if ((source.getSubSources() == (null))) {
        for (Source subSource : parentList) {
          if (source.getName().contains(subSource.getName())) {
            parent = subSource.getName();
          }      
          if ((source.getName().contains("AES")) || (source.getName().contains("IPP")) 
              || (source.getName().contains("KALAELOA")) || 
              (source.getName().contains("HPOWER"))) {
            parent = "IPP";        
          } 
        }
      }
      else {
        if (source.getName().contains("SIM_OAHU_GRID")) {
          parent = "  ";
        }
        else {
          parent = "SIM_OAHU_GRID";
        }
      }
      System.out.format(format, source.getName(), parent, source.getDescription());
      
    }
    }
    catch (MiscClientException mce) {
      return clientError;
    }
    catch (BadXmlException bxe) {
      return xmlError;
    }
    catch (NotAuthorizedException nae) {
      return notAuthError;
    }
    return "";
  }     
}